package com.zsr.chapter03.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author zsr
 * @Description ServletContext接口实现数据共享
 * @Version 1.0
 */
public class ServletDemo4 extends HttpServlet {
    @Override
    public void init() throws ServletException {
        // 给次数设置一个初始值 0
        int count = 0;
        // 将 0 存入到 ServletContext中
        getServletContext().setAttribute("count", count);

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        //获取ServletContext对象
        ServletContext context = getServletContext();
        //取出域对象中的count属性值
        int count=Integer.parseInt(context.getAttribute("count").toString());
        count+=1;
        //重新存入
        context.setAttribute("count", count);
        response.getWriter().print("欢迎光临本网站！这是您第"+count+"次访问");

    }
}
